<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2>医疗排班系统注册</h2>
      <el-form 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        label-width="80px"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="registerForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select v-model="registerForm.roleId" placeholder="请选择角色">
            <el-option 
              v-for="item in roles" 
              :key="item.id" 
              :label="item.roleName" 
              :value="item.id" />
        </el-select>
        </el-form-item>

        <el-form-item label="科室" prop="departmentId">
          <el-select v-model="registerForm.departmentId" placeholder="请选择科室">
            <el-option 
              v-for="item in departments" 
              :key="item.id" 
              :label="item.departmentName" 
              :value="item.id" />
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="loading">
            注册
          </el-button>
          <el-button @click="goToLogin">已有账号？去登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addUsertable } from '@/api/usertable'
import { listDepartment } from '@/api/department'
import { listRole } from '@/api/role'

const router = useRouter()
const registerForm = reactive({
  userName: '',
  password: '',
  confirmPassword: '',
  gender: 0,
  roleId: null,
  departmentId: null
})

const registerRules = ref({
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }]
})

const loading = ref(false)
const registerFormRef = ref(null)

const handleRegister = async () => {
  try {
    loading.value = true
    await registerFormRef.value.validate()
    
    const { confirmPassword, ...userData } = registerForm
    await addUsertable(userData)
    
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请重试')
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const departments = ref([])
const roles = ref([])

const fetchDepartments = async () => {
  try {
    const res = await listDepartment()
    departments.value = res
  } catch (error) {
    ElMessage.error('获取科室列表失败: ' + error.message)
  }
}

const fetchRoles = async () => {
  try {
    const res = await listRole()
    roles.value = res
  } catch (error) {
    ElMessage.error('获取角色列表失败: ' + error.message)
  }
}

onMounted(() => {
  fetchDepartments()
  fetchRoles()
})
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.register-card {
  width: 400px;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>